package cn.jdy.plugins.service;

import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jdy.framework.db.hibernate.BaseDao;
import cn.jdy.framework.exception.BaseException;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.platform.entity.ConfValue;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.entity.Line;


/**
 * @title 商家管理后台操作
 * @author jga
 * @since 1-12-2015
 */
@Service
public class LineService extends BaseDao<Line>{

	@Autowired
	private ConfService confService;
	
	/**
	 * 按条件查询
	 * @param sp
	 * 
	 * @return
	 */
	public List<Line> query(Line sp){
		if(sp==null) return super.findAll();
		if(sp.getiDisplayLength() > 0){
	     return super.find(createFilter(sp),sp.getiDisplayStart(),sp.getiDisplayLength());
			}
		return super.find(createFilter(sp));
	}
	 public List<Line> querypage(Line sp){
	       return super.find(createFilter(sp),sp.getPageNo(),18);
	  }
	public Long count(Line sp){
		return super.count(createFilter(sp));
	}
	/**
	 * 拼装条件
	 * @param sp
	 * 
	 * @return
	 */
	private DetachedCriteria createFilter(Line sp){
		DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
		if(!StringUtil.isNullOrEmpty(sp.getName())) {
	        dc.add(Restrictions.like("name", sp.getName(),MatchMode.ANYWHERE));
		} 
	
		if(!StringUtil.isNullOrEmpty(sp.getOrganid())) {
	        dc.add(Restrictions.like("organid", sp.getOrganid(),MatchMode.ANYWHERE));
		} 
    if(!StringUtil.isNullOrEmpty(sp.getCreateTime())&&!",".equals(sp.getCreateTime())) {
   
        if( sp.getCreateTime().split(",").length>1){
          dc.add(Restrictions.between("createTime", sp.getCreateTime().split(",")[0], sp.getCreateTime().split(",")[1]));
        }else{
          dc.add(Restrictions.like("createTime", sp.getCreateTime(),MatchMode.ANYWHERE));
        }
     
    }
	

		dc.addOrder(Order.desc("createTime"));
			return dc;
	}
	/**
	 * 删除
	 * @param sp:一个Line对象

	@Transactional
    public void delLine(Line sp){
		StringBuilder sql = new StringBuilder("delete ");
	    sql.append(entityClass.getSimpleName());
	    sql.append(" where ");
	        sql.append("and id").append("=").append(sp.getId());
	        hibernateTemplate.bulkUpdate(sql.toString(), null);
	}   */
  public List<Line> findbytype(int type, String addres, int i, int limitMax) {
    DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
    dc.add(Restrictions.eq("status", "1"));
        if(null != addres){
          dc.add(Restrictions.eq("address", addres));
        }
      if(type==0){// 根据类排序，0 表示目前根据创建时间排序 ， 以后可能会根据推广，销售量等等排序
        dc.addOrder(Order.desc("createTime"));
      }else{
        //以后会有字段或者方案
      }
      
      return super.find(dc,i,limitMax);
  }
  /**
	 *  删除
	 *
	 * @return String 删除用户信息的成功、失败信息
	 * @description: 删除指定用户标识的系统用户信息, 对多个系统用户信息的删除操作
	 * @param: id 用户标识（多个用户时用,号隔开）
	 * @author:jga
	 * @date: 2017-03-23 16:40
	 */
	@Transactional
	public String delUserById(String userIds) {
		String backInfo = "0";
		try {
			String[] ids = userIds.split(",");
			// 删除用户
			super.delete(ids, "id");
			//删除线路清空所有使用此线路的直播间
			String s="";
			for (int i = 0; i < ids.length; i++) {
				if(ids.length>0){
					s +="'"+ids[i]+"',";
				}
			}
			if (ids.length>0) {
				s=s.substring(0, s.length()-1);
			} else {
				s=userIds;
			}
				String sql="UPDATE live SET mainurl=null,mainname=null,liveurl=null WHERE mainid IN("+s+")";
				SQLQuery sqlQuery = em().createSQLQuery(sql);
				sqlQuery.executeUpdate();
			backInfo = "1";
		} catch(Exception e) {
			backInfo = "0"; // 删除失败
			BaseLog.e(this.getClass(), "删除线路", e);
			throw new BaseException("删除线路人员出错！", e);
		}
		return backInfo;
	}

}
